const OpenAIApi = require('openai');

const openai = new OpenAIApi({
  apiKey: 'sk-bf8be814cb074054b2d28141aed731a4',
  baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
});

module.exports = (router, prefix = '') => {
  router.get(`${prefix}/api/test`, async (ctx) => {
    ctx.body = { message: 'API is working' };
  });

  router.post(`${prefix}/api/openai`, async (ctx) => {
    try {
      const { prompt, context } = ctx.request.body;
      
      // 创建非流式响应
      const response = await openai.chat.completions.create({
        model: "qwen-max",
        messages: [
          { role: "system", content: "You are a helpful assistant." },
          { role: "user", content: "你是一个内容优化助手，你需要根据用户的需求和上下文，优化和完善用户需要优化和完善的内容" },
          { role: "user", content: "这是用户需要优化和完善的内容" + JSON.stringify(prompt) },
          { role: "user", content: "这是这个模块的上下文" + JSON.stringify(context) },
          { role: "user", content: "请直接返回给我结果，结果将直接插入富文本编辑器。示例：<p>测试</p>" },
        ],
        stream: false, // 禁用流式传输
      });

      // 获取完整响应
      const content = response.choices[0]?.message?.content || '';
      
      // 返回完整JSON响应
      ctx.body = { 
        content: content,
        fullResponse: response 
      };
      
    } catch (error) {
      console.error('Error in API call:', error);
      ctx.status = 500;
      ctx.body = { 
        error: 'API call failed',
        details: error.message 
      };
    }
  });
};